(function ($) {
    /*
       虚表联合编辑器
    */
    $.fn.yqUnitEdit = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqUnitEdit.methods[opts](this, param);
        }

        return this.each(function () {
            $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqUnitEdit") {
                var opt_= options($this);
                opt_ = {
                    ajaxUrl: opt_.ajaxUrl,
                    ui_mask: opt_.ui_mask,
                    data:opt_.data,
                    isEdit:opt_.isEdit,
                    beforeBindingTitle:opt_.beforeBindingTitle,
                    afterBindingTitle:opt_.afterBindingTitle,
                };

                var $uniqueID = $this.attr("ID");
                destroy($this);
                $this = $("#" + $uniqueID);
                opt = $.extend({}, opt_, opts);
            }
            else {
                opt = $.extend({}, $.fn.yqUnitEdit.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined) {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            if (opt.width === undefined && $this.width() > 0) {
                opt.width = $this.width();
            } else if (typeof opt.width == "string") { //转换编辑尺寸
                var r_str = opt.width.substring(opt.width.length - 1, opt.editModeW.length);
                if (r_str == "%") {
                    var wSacle = parseInt(opt.width.substring(0, opt.width.length - 1));
                    opt.width = parseInt(wSacle * $(window).width() / 100);
                } else {
                    opt.width = parseInt(opt.width);
                }
            }

            if (opt.height === undefined && $this.height() > 0) {
                opt.height = $this.height();
            } else if (typeof opt.height == "string") { //转换编辑尺寸
                var r_str = opt.height.substring(opt.height.length - 1, opt.editModeH.length);
                if (r_str == "%") {
                    var wSacle = parseInt(opt.height.substring(0, opt.height.length - 1));
                    opt.height = parseInt(wSacle * $(window).height() / 100);
                } else {
                    opt.height = parseInt(opt.height);
                }
            }

            //变量信息
            $this.data("unitedit_opt", opt);
            $this.data("yqtype", "yqUnitEdit");

            init_ui_before($this);
        });
    };

    $.fn.yqUnitEdit.defaults = {
        ajaxUrl: "/_db.html",
        ui_mask: {
            ui_title: 17,  //17-attr,15-table,16-trees
            param: {
                titles: [{
                    is_func: false,
                    name: "code",
                    ui_title: "Code",
                    ui_type: 2,
                    ui_width: 80,
                    ui_visible: true,
                    ui_readonly: false,
                    ui_mask: {}
                }, {
                    is_func: false,
                    name: "name",
                    ui_title: "Name",
                    ui_type: 2,
                    ui_width: 80,
                    ui_visible: true,
                    ui_readonly: false,
                    ui_mask: {}
                }]
            }
        },  //数据列配置对象
        data: {},
        isEdit: true,
        beforeBindingTitle: function (ui_mask, callback) {
            callback(ui_mask);
        }, //标题绑定前
        afterBindingTitle: function () { },   //标题绑定后
    };

    $.fn.yqUnitEdit.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        resize: function (jq, params) {
            resize($(jq[0]), params);
        },
        clear: function (jq, data) {
            clear($(jq[0]), []);
        },
        setData: function (jq, data) {
            setData($(jq[0]), data);
        },
        getData: function (jq) {
            return getData($(jq[0]));
        },
        isEdit: function (jq, tf) {
            isEdit($(jq[0]), tf);
        }
    };

    function options($object) {
        return $object.data("unitedit_opt");
    }

    function destroy($object) {
        var opt = options($object);
        if (opt.ui_mask.ui_type == 17) {
            if (opt.ui_mask.editType == 1) {
                opt.$div.yqAttrEdit("destroy");
            } else if (opt.ui_mask.editType == 2) {
                opt.$div.yqFormEdit("destroy");
            }
        } else if (opt.ui_mask.ui_type == 15) {
            opt.$div.yqTableEdit("destroy");
        } else if (opt.ui_mask.ui_type == 16) {
            opt.$div.yqTreeEdit("destroy");
        }

        $object.empty();

        $object.removeData("unitedit_opt");
        $object.removeData("yqtype");
    }

    function resize($object, params) {
        var opt = options($object);
        if (typeof params == "object") {
            opt.width = parseInt(params.width);
            opt.height = parseInt(params.height);
        }

        if (opt.ui_mask.ui_type == 17) {
            if (opt.ui_mask.editType == 1) {
                opt.$div.yqAttrEdit("resize", {
                    width: opt.width,
                    height: opt.height
                });
            } 
        } else if (opt.ui_mask.ui_type == 15) {
            opt.$div.yqTableEdit("resize", {
                width: opt.width,
                height: opt.height
            });
        } else if (opt.ui_mask.ui_type == 16) {
            opt.$div.yqTreeEdit("resize", {
                width: opt.width,
                height: opt.height
            });
        }
    }

    function init_ui_before($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");
        $object.empty();
        opt.$div=$('<div id="'+ $uniqueID  +'_div"></div>');
        opt.$div.css({width:opt.width,height:opt.height});
        $object.append( opt.$div);
        $object.removeAttr("style");

        opt.beforeBindingTitle.call($object, opt.ui_mask,
            function (ui_mask) {
                opt.ui_mask = ui_mask;
                if (opt.ui_mask.ui_type == 17) {
                    init_ui_attr($object);
                } else if (opt.ui_mask.ui_type == 15) {
                    init_ui_table($object);
                } else if (opt.ui_mask.ui_type == 16) {
                    init_ui_tree($object);
                }
            });
    }

    function init_ui_attr($object) {
        var opt = options($object);
        if (!(opt.ui_mask.editType == 1 ||
            opt.ui_mask.editType == 2)) {
            opt.ui_mask.editType = 1;
        }

        var titles = opt.ui_mask.param.titles;

        if (opt.ui_mask.editType == 1) {
            opt.$div.yqAttrEdit({
                ajaxUrl: "/_db.html",
                titles: titles,
                row: opt.data,
                loadDefault: true,   //加载默认值
                beforeBindingTitle: function (titles, callback) {
                    callback(titles);
                }, //标题绑定前
                afterBindingTitle: function () {
                    opt.afterBindingTitle.call($object);
                },   //标题绑定后
                endEditing: function (index, row) {   //ok.....
                    console.log("endEditing", index, row);
                },
            });
        } else if (opt.ui_mask.editType == 2) {
            opt.$div.removeAttr("style");
            var model = opt.ui_mask.param.model;
            if (model === undefined) {
                model = null;
            }
            opt.$div.yqFormEdit({
                ajaxUrl: "/_db.html",
                titles: titles,
                model: model,
                row: opt.data,
                loadDefault: false,   //加载默认值
                isEdit: true,
                blankTag: "*",     //值不能为空，标题附加标记
                afterBindingTitle: function () {
                    opt.afterBindingTitle.call($object);
                },   //标题绑定后
            });
        }
    }

    function init_ui_table($object) {
        var opt = options($object);

        opt.$div.yqTableEdit({
            ajaxUrl: "/_db.html",
            titles: opt.ui_mask.param.titles,  //数据列配置对象
            rows: opt.data,
            editModeW: opt.width, //模态编辑器宽度 格式为 800（数字）
            editModeH: opt.height, //模态编辑器高度 格式为 600（数字）
            isEdit: true,
            isAdd: true,
            isDel: true,
            beforeBindingTitle: function (titles, callback) {
                console.log("beforeBindingTitle", titles);
                callback(titles);
            }, //标题绑定前
            afterBindingTitle: function () {
                opt.afterBindingTitle.call($object);
            }, //标题绑定后       
            endEditing: function (index, row) {   //ok.....
                console.log("endEditing", index, row);
            },
            beforeAdd: function (rows, row, callback) {
                console.log("beforeAdd", rows, row);
                callback(row);
            },
        });
    }

    function init_ui_tree($object) {
        var opt = options($object);

        opt.$div.yqTreeEdit({
            ajaxUrl: "/_db.html",
            displayMember: opt.ui_mask.displayMember,          //显示字段
            titles: opt.ui_mask.param.titles,  //数据列配置对象
            data: opt.data,
            editModeW: opt.width, //模态编辑器宽度 格式为 800（数字）
            editModeH: opt.height, //模态编辑器高度 格式为 600（数字）
            isEdit: true,
            beforeBindingTitle: function (titles, callback) {
                console.log("beforeBindingTitle", titles);
                callback(titles);
            }, //标题绑定前
            afterBindingTitle: function () {
                opt.afterBindingTitle.call($object);
            },   //标题绑定后
            beforeAdd: function (rows, row, callback) {
                console.log("beforeAdd", rows, row);
                callback(row);
            },
            endEditing: function (index, row) {   //ok.....
                console.log("endEditing", index, row);
            },
        });
    }

    function clear($object) {
        var opt = options($object);
        opt.data = data;
        if (opt.ui_mask.ui_type == 17) {
            if (opt.ui_mask.editType == 1) {
                opt.$div.yqAttrEdit("clear");
            } else if (opt.ui_mask.editType == 2) {
                opt.$div.yqFormEdit("clear");
            }
        } else if (opt.ui_mask.ui_type == 15) {
            opt.$div.yqTableEdit("clear");
        } else if (opt.ui_mask.ui_type == 16) {
            opt.$div.yqTreeEdit("clear");
        }
    }

    function setData($object, data) {
        var opt = options($object);
        opt.data = data;
        if (opt.ui_mask.ui_type == 17) {
            if (opt.ui_mask.editType == 1) {
                opt.$div.yqAttrEdit("setRow", data);
            } else if (opt.ui_mask.editType == 2) {
                opt.$div.yqFormEdit("setRow", data);
            }
        } else if (opt.ui_mask.ui_type == 15) {
            opt.$div.yqTableEdit("setRows", data);
        } else if (opt.ui_mask.ui_type == 16) {
            opt.$div.yqTreeEdit("setData", data);
        }
    }

    function getData($object) {
        var opt = options($object);
        if (opt.ui_mask.ui_type == 17) {
            if (opt.ui_mask.editType == 1) {
                opt.data =  opt.$div.yqAttrEdit("getRow");
            } else if (opt.ui_mask.editType == 2) {
                opt.data =  opt.$div.yqFormEdit("getRow");
            }
        } else if (opt.ui_mask.ui_type == 15) {
            opt.data =  opt.$div.yqTableEdit("getRows");
        } else if (opt.ui_mask.ui_type == 16) {
            opt.data =  opt.$div.yqTreeEdit("getData");
        }

        return opt.data;
    }

    function isEdit($object, tf) {
        var opt = options($object);
        opt.isEdit = tf;
        if (opt.ui_mask.ui_type == 17) {
            if (opt.ui_mask.editType == 1) {
                opt.$div.yqAttrEdit("isEdit", tf);
            } else if (opt.ui_mask.editType == 2) {
                opt.$div.yqFormEdit("isEdit", tf);
            }
        } else if (opt.ui_mask.ui_type == 15) {
            opt.$div.yqTableEdit("isEdit", tf);
        } else if (opt.ui_mask.ui_type == 16) {
            opt.$div.yqTreeEdit("isEdit", tf);
        }
    }
})(jQuery);